package Hot100.LinkNode;

import DMSXL._2023Before.ListNode_.ListNode;

public class mergeKLists {
    public static void main(String[] args) {
        int[][] values = {{1,4,5},{1,3,4},{2,6}};
        ListNode[] heads = new ListNode[values.length];
        int[] count = new int[values.length];
        ListNode[] prevs = new ListNode[values.length];
        for (int i = 0; i < values.length; i++) {
            for (int j = 0; j < values[i].length; j++) {
                if(count[i] == 0){
                    ListNode temp = new ListNode(values[i][j]);
                    heads[i] = temp;
                    prevs[i] = temp;
                    count[i]++;
                }else {
                    ListNode temp = new ListNode(values[i][j]);
                    prevs[i].next =temp;
                    prevs[i] = prevs[i].next;
                }
            }
        }
        ListNode ans = mergeKLists(heads);
        while (ans != null){
            System.out.println(ans.val);
            ans = ans.next;
        }
        System.out.println(mergeKLists(heads));

    }
    public static ListNode mergeKLists(ListNode[] lists) {
        if (lists.length == 0)
            return null;
        ListNode head = null;
        ListNode pre = new ListNode();
        ListNode[] prevs = lists;
        int min = 0;
        int index = 0;
        int count = 0;
        int zero = 0;
        Boolean out = true;
        while(out){
            min = Integer.MAX_VALUE;
            zero = 0;
            for (int i = 0; i < prevs.length; i++) {
                if(prevs[i] == null)
                    continue;
                if(min > prevs[i].val){
                    zero++;
                    index = i;
                    min = prevs[i].val;
                }
            }
            if(zero == 0)
                break;
            ListNode temp = new ListNode(min);
            if(count++ == 0){
                head = temp;
                pre = head;
                prevs[index] = prevs[index].next;
            }else {
                pre.next = temp;
                pre = pre.next;
                prevs[index] = prevs[index].next;
            }
        }
        return head;
    }
}
